﻿<%@ WebHandler Language="C#" Class="ZSContainerCheckInfoManageHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
using Newtonsoft.Json;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
/// <summary>
/// add by longb 2022-06-09
/// 检验作业、故检作业相关业务
/// </summary>
public class ZSContainerCheckInfoManageHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    QulityCheckBusiness Q_check = new QulityCheckBusiness();
    uLMSCommonIBusiness m_Common = uMESBusinessFactory.instance.GetuLMSCommonObject();
    private uLMSCheckIBusiness m_CheckObj = uMESBusinessFactory.instance.GetuLMSCheckObject();
    private uLMSCommonIBusiness m_CommonBusiness = uMESBusinessFactory.instance.GetuLMSCommonObject();
    private uLMSWorkReportIBusiness m_ReportObj = uMESBusinessFactory.instance.GetuLMSWorkReportObject();
    private uLMSDispatchIBusiness m_DispatchObj = uMESBusinessFactory.instance.GetuLMSDispatchObject();
    private uLMSStepCheckPointIBusiness m_CheckPointObj = uMESBusinessFactory.instance.GetuLMSStepCheckPointObject();
    private uLMSContainerIBusiness m_ContainerObj = uMESBusinessFactory.instance.GetuLMSContainerObject();
    private uLMSScrapInfoIBusiness m_ScrapInfoBusiness = uMESBusinessFactory.instance.GetuLMSScrapInfoBusinessObject();
    private uLMSDealFaultBillIbusiness m_DealFaultBill = uMESBusinessFactory.instance.GetuLMSdealFaultBillObject();
    private uLMSPartPlanIBusiness m_PartPlanObj = uMESBusinessFactory.instance.GetuLMSPartPlanObject();
    private uLMSQualityHistoryRecordIBusiness m_QualityHistory = uMESBusinessFactory.instance.GetQualityHistoryRecordObject();
    private uMESCommonIBusiness CommonObject = uMESBusinessFactory.instance.GetCommonObject();
    private uLMSIssueERPMaterialIbusiness m_issueData = uMESBusinessFactory.instance.GetuLMSIssueERPMaterialObject();
    private uLMSUnqualifiedIBusiness m_UnqualifiedData = uMESBusinessFactory.instance.GetuLMSUnqualifiedObject();
    #region 页面初始化
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "GetBigSmallData": //查询配套件信息
                    GetBigSmallData(context);
                    break;
                case "GetSpecData": //查询工序Session信息
                    GetSpecData(context);
                    break;
                case "GetUnit"://查询责任单位
                    GetUnit(context);
                    break;
                case "GetEmployees":
                    GetEmployees(context);
                    break;
                case "SaveQulityQuestionDeal"://质量问题处置
                    SaveQulityQuestionDeal(context);
                    break;
                case "GetQulityQuestionDeal"://查询质量问题处置信息
                    GetQulityQuestionDeal(context);
                    break;
                case "GetQualityQuestionDealExamine"://质量问题处置单审核--查询
                    GetQualityQuestionDealExamine(context);
                    break;
                case "QualityQuestionDealExamine"://质量问题处置单审核--审核
                    QualityQuestionDealExamine(context);
                    break;
                case "GetNotCheckContainer":
                    GetNotCheckContainer(context);
                    break;
                case "GetWorkflowStep":
                    GetWorkflowStep(context);
                    break;
                case "GetZSWorkFlowStepAndStepInfo":
                    GetZSWorkFlowStepAndStepInfo(context);
                    break;
                case "GetDealFaultBillAndScrap":
                    GetDealFaultBillAndScrap(context);
                    break;
                case "CheckQualified"://检验合格
                    CheckQualified(context);
                    break;
                case "GetLossReason":
                    GetLossReason(context);
                    break;
                case "GetProductCollectInfo"://检验操作--查询配套件
                    GetProductCollectInfo(context);
                    break;
                case "GetIssueMarterialInfo"://检验操作--查询配套件--集件信息
                    GetIssueMarterialInfo(context);
                    break;
                case "SaveCheckResultData"://保存检验信息
                    SaveCheckResultData(context);
                    break;
                case "InitUnqualified":
                    InitUnqualified(context);//初始化不合格审理申请页面数据获取
                    break;
                case "GetLossReasonByGroupID"://缺陷原因-代码组ID--查询缺陷代码
                    GetLossReasonByGroupID(context);
                    break;
                case "FillLossSequenceAndTxtData"://缺陷序号和短文本描述到文本框中
                    FillLossSequenceAndTxtData(context);
                    break;
                case"InsertUnqualifiedData":
                    InsertUnqualifiedData(context);
                    break;
                case"getScanContainerData":
                    getScanContainerData(context);
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    #endregion

    #region 【质量问题处置】--方法
    /// <summary>
    /// 查询配套件信息
    /// </summary>
    /// <param name="context"></param>
    protected void GetBigSmallData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        result.Result = true;
        string workflowstepid = context.Request["workflowstepid"].ToString();
        string ContainerNo = context.Request["ContainerNo"].ToString();
        var Condition = new Dictionary<string, string>();
        Condition.Add("ContainerNo", ContainerNo);//任务单号
        Condition.Add("workflowstepid", workflowstepid);
        result.DBTable = Q_check.GetQualityDealBigSmallData(Condition);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 查询工序Session信息
    /// </summary>
    /// <param name="context"></param>
    protected void GetSpecData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        result.ReturnData = context.Session["QQwgResult"];
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取责任单位
    /// </summary>
    /// <param name="context"></param>
    protected void GetUnit(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        result.Result = true;
        result.DBTable = m_Common.GetFactory(new Dictionary<String, String>());//AddDutyUnit();
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 查询所有责任人
    /// </summary>
    /// <param name="context"></param>
    protected void GetEmployees(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        string Name = context.Request["Name"].ToString();
        var para = new Dictionary<String, String>();
        para.Add("Name", Name);
        result.DBTable = Q_check.GetEmployees(para);//AddDutyUnit();
        result.Result = result.DBTable.Rows.Count > 0;
        result.Message = result.Result ? "" : "根据条件匹配不到相应责任人信息";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 查询零件处置单信息
    /// </summary>
    /// <param name="context"></param>
    protected void GetQulityQuestionDeal(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        string productitemname = context.Request["productitemname"].ToString();
        string issueerpmalterialid = context.Request["issueerpmalterialid"].ToString();
        string togetherflag = context.Request["togetherflag"].ToString();
        var para = new Dictionary<string, string>();
        para.Add("productitemname", productitemname);
        para.Add("togetherflag", togetherflag);
        para.Add("IssueERPMaterialID", issueerpmalterialid);
        result.DBTable = Q_check.GetQulityQuestionDeal(para);
        result.Result = result.DBTable.Rows.Count > 0;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 质量问题保存
    /// </summary>
    /// <param name="context"></param>
    protected void SaveQulityQuestionDeal(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        List<ExcuteEntity> List = new List<ExcuteEntity>();
        if (dt.Rows.Count > 0)
        {
            var qualityhistoryrecordid = dt.Rows[0]["qualityhistoryrecordid"].ToString();
            var type = string.IsNullOrWhiteSpace(qualityhistoryrecordid) ? ExcuteEntity.ExcuteTypeEnum.insert : ExcuteEntity.ExcuteTypeEnum.update;
            var InsertEntity = new ExcuteEntity("QUALITYHISTORYRECORD", type);
            List<FieldEntity> InsertList = new List<FieldEntity>();
            if (string.IsNullOrWhiteSpace(qualityhistoryrecordid))
            {
                InsertList.Add(new FieldEntity("qualityhistoryrecordid", Guid.NewGuid().ToString(), FieldEntity.FieldTypeEnum.Str));//唯一ID--
                InsertList.Add(new FieldEntity("createtime", DateTime.Now, FieldEntity.FieldTypeEnum.DateTime));//创建日期---
                InsertList.Add(new FieldEntity("isadd", "1", FieldEntity.FieldTypeEnum.Str));//是否新增---
                InsertList.Add(new FieldEntity("isuse", "0", FieldEntity.FieldTypeEnum.Str));//是否在用---
                InsertList.Add(new FieldEntity("createemployeeid", m_UserInfo.EmployeeID.ToString(), FieldEntity.FieldTypeEnum.Str));//创建人---
                var maxSequence = Q_check.GetQulityQuestionDeal_MaxSequence();
                InsertList.Add(new FieldEntity("SEQUENCE", maxSequence, FieldEntity.FieldTypeEnum.Str));//顺序号
                var strSequence = "000000" + maxSequence;
                var dealName = "WT-" + DateTime.Now.ToString("yyyy") + "-" + m_UserInfo.FactoryCode + "-" + strSequence.Substring(strSequence.Length - 4);
                InsertList.Add(new FieldEntity("DealNAME", dealName, FieldEntity.FieldTypeEnum.Str));//处置单号
            }

            InsertList.Add(new FieldEntity("WorkCenterID", m_UserInfo.WorkCenterID.ToString(), FieldEntity.FieldTypeEnum.Str));//发生工区
            InsertList.Add(new FieldEntity("OrgFactoryID", m_UserInfo.FactoryID.ToString(), FieldEntity.FieldTypeEnum.Str));//提交单位
            InsertList.Add(new FieldEntity("mfgOrderName", dt.Rows[0]["mfgOrderName"].ToString(), FieldEntity.FieldTypeEnum.Str));//订单号
            InsertList.Add(new FieldEntity("productname", dt.Rows[0]["productname"].ToString(), FieldEntity.FieldTypeEnum.Str));//部件号
            InsertList.Add(new FieldEntity("engineno", dt.Rows[0]["engineno"].ToString(), FieldEntity.FieldTypeEnum.Str));//发动机号
            InsertList.Add(new FieldEntity("workflowstepid", dt.Rows[0]["workflowstepid"].ToString(), FieldEntity.FieldTypeEnum.Str));//工序ID
            InsertList.Add(new FieldEntity("productItemName", dt.Rows[0]["productItemName"].ToString(), FieldEntity.FieldTypeEnum.Str));//零件名称
            InsertList.Add(new FieldEntity("ContainerNo", dt.Rows[0]["PRODUCTBATCHNO"].ToString(), FieldEntity.FieldTypeEnum.Str));//批次号
            InsertList.Add(new FieldEntity("togetherflag", dt.Rows[0]["togetherflag"].ToString(), FieldEntity.FieldTypeEnum.Str));//任务单号
            InsertList.Add(new FieldEntity("FactoryID", dt.Rows[0]["FactoryID"].ToString(), FieldEntity.FieldTypeEnum.Str));//责任单位
            InsertList.Add(new FieldEntity("IssueERPMaterialID", dt.Rows[0]["IssueERPMaterialID"].ToString(), FieldEntity.FieldTypeEnum.Str));//装配信息表ID
            InsertList.Add(new FieldEntity("CheckNO", dt.Rows[0]["CheckNO"].ToString(), FieldEntity.FieldTypeEnum.Str));//检验编号
            InsertList.Add(new FieldEntity("PartCategory", dt.Rows[0]["PartCategory"].ToString(), FieldEntity.FieldTypeEnum.Str));//零件类别
            InsertList.Add(new FieldEntity("DUTYEMPLOYEEID", dt.Rows[0]["DUTYEMPLOYEEID"].ToString(), FieldEntity.FieldTypeEnum.Str));//责任者
            InsertList.Add(new FieldEntity("UnqualifiedNum", dt.Rows[0]["UnqualifiedNum"].ToString(), FieldEntity.FieldTypeEnum.Str));//不合格数
            InsertList.Add(new FieldEntity("UnqualifiedDescribe", dt.Rows[0]["UnqualifiedDescribe"].ToString(), FieldEntity.FieldTypeEnum.Str));//不合格描述
            InsertList.Add(new FieldEntity("IsKeyFeatures", string.IsNullOrWhiteSpace(dt.Rows[0]["IsKeyFeatures"].ToString()) ? "0" : dt.Rows[0]["IsKeyFeatures"].ToString(), FieldEntity.FieldTypeEnum.Str));//是否有关键特性
            InsertList.Add(new FieldEntity("IsImportantFeatures", string.IsNullOrWhiteSpace(dt.Rows[0]["IsImportantFeatures"].ToString()) ? "0" : dt.Rows[0]["IsImportantFeatures"].ToString(), FieldEntity.FieldTypeEnum.Str));//是否有重要特性
            InsertList.Add(new FieldEntity("ISDESIGNBASISFEATURES", string.IsNullOrWhiteSpace(dt.Rows[0]["IsDesignBasisFeatures"].ToString()) ? "0" : dt.Rows[0]["IsDesignBasisFeatures"].ToString(), FieldEntity.FieldTypeEnum.Str));//是否有设计基准要素
            InsertList.Add(new FieldEntity("problemNature", dt.Rows[0]["problemNature"].ToString(), FieldEntity.FieldTypeEnum.Str));//问题性质
            InsertEntity.ExcuteFileds = InsertList;
            if (!string.IsNullOrWhiteSpace(qualityhistoryrecordid))
            {
                List<FieldEntity> whereList = new List<FieldEntity>();
                whereList.Add(new FieldEntity("qualityhistoryrecordid", qualityhistoryrecordid, FieldEntity.FieldTypeEnum.Str));
                InsertEntity.WhereFileds = whereList;
            }
            List.Add(InsertEntity);
        }
        result.Result = DatabaseAccess.DBUtility.DatabaseHelper.ExecuteDataByEntitys(List);
        if (result.Result) { result.Message = "操作成功"; } else { result.Message = "操作失败"; }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    #endregion

    #region 质量问题处置单审核--方法
    /// <summary>
    /// 质量问题处置单审核--查询
    /// </summary>
    /// <param name="context"></param>
    protected void GetQualityQuestionDealExamine(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        var para = new Dictionary<string, string>();
        para.Add("dealname", dt.Rows[0]["dealname"].ToString());
        para.Add("mfgordername", dt.Rows[0]["ordername"].ToString());
        para.Add("productname", dt.Rows[0]["productname"].ToString());
        para.Add("startedate", dt.Rows[0]["startedate"].ToString());
        para.Add("enddate", dt.Rows[0]["enddate"].ToString());
        result.DBTable = Q_check.GetQualityQuestionDealExamine(para);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 质量问题处置单审核--审核
    /// </summary>
    /// <param name="context"></param>
    protected void QualityQuestionDealExamine(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        var para = new Dictionary<string, string>();
        para.Add("employeeid", m_UserInfo.EmployeeID.ToString());
        para.Add("qualityhistoryid", context.Request["ids"].ToString());
        var count = Q_check.QualityQuestionDealExamine(para);
        if (count > 0) { result.Result = true; result.Message = "审核成功"; } else { result.Result = false; result.Message = "审核失败"; }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    #endregion
    /// <summary>
    /// 查询待检验批次任务单数据
    /// </summary>
    /// <param name="context"></param>
    private void GetNotCheckContainer(HttpContext context)
    {
        var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        var para = new Dictionary<string, string>();
        if (!string.IsNullOrWhiteSpace(dic["ContainerNo"]))
        {
            para.Add("ContainerNo", dic["ContainerNo"]);
        }
        if (!string.IsNullOrWhiteSpace(dic["Machine"]))
        {
            para.Add("MachineStart", dic["Machine"]);
        }
        if (!string.IsNullOrWhiteSpace(dic["ProductName"]))
        {
            para.Add("ProductName", dic["ProductName"]);
        }
        if (!string.IsNullOrWhiteSpace(dic["TaskType"]))
        {
            para.Add("TaskType", dic["TaskType"]);
        }

        para.Add("FactoryID", m_UserInfo.FactoryID);
        para.Add("PageSize", dic["pageSize"]);
        para.Add("CurrentPageIndex", dic["currentPage"]);
        var oResult = new uMESProcessResult();
        if (string.IsNullOrWhiteSpace(dic["PartType"]))
        {
            oResult = m_CheckObj.GetNotCheckContainer(para);
        }
        else
        {
            para.Add("PartType", dic["PartType"]);
            oResult = m_CheckObj.GetGJCheckContainer(para);
        }
        context.Response.Write(JsonConvert.SerializeObject(oResult));
    }
    /// <summary>
    /// 查询工序
    /// </summary>
    /// <param name="context"></param>
    private void GetWorkflowStep(HttpContext context)
    {
        var para = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        var dt = m_CheckObj.GetZSWorkFlowStepAndStepInfo(para).Tables["DtStep"];
        var workflowtype = dt.Rows.Count > 0 && !string.IsNullOrWhiteSpace(dt.Rows[0]["workflowtype"].ToString()) ? dt.Rows[0]["workflowtype"].ToString() : string.Empty;
        if (workflowtype.IndexOf("施工") >= 0)
        {
            DataRow[] drs = dt.Select("( teamname is not null and teamname not like '%故检%') or teamname is null");
            dt = drs.CopyToDataTable();
        }
        var oResult = new uMESProcessResult();
        oResult.Result = true;
        oResult.DBTable = dt;
        context.Response.Write(JsonConvert.SerializeObject(oResult));
    }
    /// <summary>
    /// 查询工步信息
    /// </summary>
    /// <param name="context"></param>
    private void GetZSWorkFlowStepAndStepInfo(HttpContext context)
    {
        var para = new Dictionary<string, string>();
        para.Add("WorkflowstepId", context.Request["WorkflowstepId"].ToString());
        para.Add("ContainerId", context.Request["ContainerID"].ToString());
        para.Add("WorkflowId", context.Request["WorkflowId"].ToString());
        DataTable dt = m_CheckObj.GetZSWorkFlowStepAndStepInfo(para).Tables["dtStepInfo"];
        var oResult = new uMESProcessResult();
        oResult.Result = true;
        oResult.DBTable = dt;
        context.Response.Write(JsonConvert.SerializeObject(oResult));
    }
    /// <summary>
    /// 查询排故单和报废单
    /// </summary>
    /// <param name="context"></param>
    private void GetDealFaultBillAndScrap(HttpContext context)
    {
        var para = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        var oResult = m_DealFaultBill.GetPGDInfo(para);
        oResult.ReturnData = m_ScrapInfoBusiness.GetZSScrapInfo(para);
        context.Response.Write(JsonConvert.SerializeObject(oResult));
    }
    private void GetLossReason(HttpContext context)
    {
        var result = new uMESProcessResult();
        result.Result = true;
        result.DBTable = m_CommonBusiness.GetLossReasonByGroupName("检验报废原因组");
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 配套件查询
    /// </summary>
    /// <param name="context"></param>
    private void GetProductCollectInfo(HttpContext context)
    {
        var para = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        var result = new uMESProcessResult();
        result.Result = true;
        DataTable bom_dt = m_CommonBusiness.GetBomByWorkflowID(para["WORKFLOWID"]);
        if (bom_dt.Rows.Count > 0)
        {
            foreach (DataRow dr in bom_dt.Rows)
            {
                // '先查询时大小件目录的
                if (dr["BILLTYPENAME"].ToString() == "PRODUCTMATERIAL")
                {
                    var collectProduct_dt = CommonObject.GetBOM(dr["BOMID"].ToString());
                    var dv = collectProduct_dt.DefaultView;
                    dv.RowFilter = String.Format("STEPINFOID='{0}'", para["STEPINFOID"]);
                    result.DBTable = dv.ToTable();
                }
            }
            // '如果大小件目录没有就查消耗件的
            if (result.DBTable.Rows.Count == 0)
            {
                var collectProduct_dt = CommonObject.GetBOM(bom_dt.Rows[0]["BOMID"].ToString());
                var dv = collectProduct_dt.DefaultView;
                //dv.RowFilter = String.Format("STEPINFOID='{0}'", para["STEPINFOID"]);
                result.DBTable = dv.ToTable();
            }
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 配套件集件查询
    /// </summary>
    /// <param name="context"></param>
    private void GetIssueMarterialInfo(HttpContext context)
    {
        var para = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        var result = new uMESProcessResult();
        result.Result = true;
        if (para["type"].Equals("1"))
        {
            result.DBTable = m_issueData.GetGJIssueMaterialIntegratedData(para);
        }
        else
        {
            result.DBTable = (DataTable)m_ReportObj.GetIssueMaterialIntegratedData(para);
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private void SaveCheckResultData(HttpContext context)
    {
        var mpara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["mdata"].ToString());//检验任务工序信息
        var paraa = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());//配套件--集件报废信息
        var dpara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["ddata"].ToString());//购代件--报废信息
        var result = new uMESProcessResult();
        if (!string.IsNullOrWhiteSpace(paraa["ScrapQty"]))
        {
            var para = new Dictionary<string, string>();
            para.Add("CheckerID", m_UserInfo.EmployeeID);
            para.Add("CheckNote", paraa["Note"]);
            para.Add("WorkerID", m_UserInfo.EmployeeID);
            para.Add("CollectErpMaterialID", paraa["CollectErpMaterialID"]);
            para.Add("IssueErpMaterialID", paraa["IssueErpMaterialID"]);
            para.Add("LossReasonID", paraa["Reason"]);
            para.Add("WorkReportMaterialRecordID", "");
            para.Add("LossQty", paraa["ScrapQty"]);
            para.Add("Containerid", mpara["CONTAINERID"]);
            para.Add("Workflowstepid", mpara["WORKFLOWSTEPID"]);
            para.Add("Stepinfoid", mpara["STEPINFOID"]);
            result.Result = m_issueData.InsertIssueERPMaterialScrapInfo(para, "ZS");
        }
        if (!string.IsNullOrWhiteSpace(dpara["ScrapQty"]))
        {
            var insertPara = new Dictionary<string, object>();
            insertPara.Add("ZSREPLACEBUYPRODUCTSCRAPINFOID", "'" + Guid.NewGuid().ToString() + "'");
            insertPara.Add("CONTAINERNO", "'" + dpara["CONTAINERNO"] + "'");
            insertPara.Add("CONTAINERID", "'" + mpara["CONTAINERID"] + "'");
            insertPara.Add("PRODUCTID", "'" + dpara["ProductID"] + "'");
            insertPara.Add("LOSSQTY", "'" + dpara["ScrapQty"] + "'");
            insertPara.Add("WORKFLOWSTEPID", "'" + mpara["WORKFLOWSTEPID"] + "'");
            insertPara.Add("STEPINFOID", "'" + mpara["STEPINFOID"] + "'");
            insertPara.Add("LOSSREASONID", "'" + dpara["Reason"] + "'");
            insertPara.Add("LOSSREASONNAME", "''");
            insertPara.Add("NOTES", "'" + dpara["Note"] + "'");
            insertPara.Add("CREATEDATE", "sysdate");
            insertPara.Add("CREATEEMPLOYEEID", "'" + m_UserInfo.EmployeeID + "'");
            insertPara.Add("CONTAINERSTEPWORKREPORTID", "'" + mpara["CONTAINERSTEPWORKREPORTID"] + "'");
            insertPara.Add("PRODUCTNAME", "'" + dpara["ProductName"] + "'");
            insertPara.Add("BATCHNO", "'" + dpara["BatchNo"] + "'");
            insertPara.Add("MFGORDERNAME", "'" + dpara["mfgordername"] + "'");
            insertPara.Add("FACTORYID", "'" + m_UserInfo.FactoryID + "'");
            result.Result = m_CommonBusiness.InsertTableInfo("ZSREPLACEBUYPRODUCTSCRAPINFO", insertPara);
        }
        //维护报工装配记录信息
        if (!string.IsNullOrWhiteSpace(paraa["Note"]))
        {
            var DTO = new ContainerStepWorkReportDTO();
            DTO.ContainerID = mpara["CONTAINERID"];
            DTO.WorkflowstepID = mpara["WORKFLOWSTEPID"];
            DTO.StepInfoID = mpara["STEPINFOID"];
            var note = string.Empty;
            var ID = m_CheckObj.VerifyZSWorkreportMaterialrRecordIsExistInfo(DTO, ref note);
            if (string.IsNullOrWhiteSpace(ID))
            {
                if (!paraa.ContainsKey("IssueErpMaterialID"))
                {
                    result.Message = "填写了报工备注信息，请选择需要添加装配";
                    result.Message = (result.Result ? "提交成功 " : "提交失败 ") + result.Message;
                    context.Response.Write(JsonConvert.SerializeObject(result));
                    return;
                }
                DTO.WorkerID = m_UserInfo.EmployeeID;
                DTO.Qty = 0;
                DTO.Note = paraa["Note"];
                DTO.IsUse = 0;
                DTO.IssueType = -1;
                DTO.IssueReason = -1;
                DTO.GuideDoc = "";
                DTO.IssueERPMaterialID = paraa["IssueErpMaterialID"];
                DTO.WorkReportMaterialRecordID = System.Guid.NewGuid().ToString();
                if (!m_ReportObj.AddWorkReportMaterialRecord(DTO))
                {
                    result.Message = "添加装配报工备注信息失败";
                }
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(note))
                {
                    DTO.WorkReportMaterialRecordID = ID;
                    DTO.Note = paraa["Note"];
                    if (!m_CheckObj.UpdateZSWorkreportMaterialrRecordNote(DTO))
                    {
                        result.Message = "修改装配报工信息备注失败";
                        result.Message = (result.Result ? "提交成功 " : "提交失败 ") + result.Message;
                        context.Response.Write(JsonConvert.SerializeObject(result));
                        return;
                    }
                }
            }
        }
        result.Message = (result.Result ? "提交成功 " : "提交失败 ") + result.Message;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 合格操作
    /// </summary>
    /// <param name="context"></param>
    private void CheckQualified(HttpContext context)
    {
        var result = new uMESProcessResult();
        //1.历史质量问题查看，有新增的必须查看，没有新增的可以不用查看
        var para = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        DataTable qdt = m_QualityHistory.GetQualityHistoryRecord(para);
        if (qdt.Select("isAdd='是'").Length > 0)
        {
            result.Message = "请确认历史质量问题";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        //2.所有选择的工序下，工步检测项是否已录入完成
        var Count = 0;
        var isNotwrok = 0;//工序工步未报工项
        var isNotcheck = 0;//工序工步未检验项
        var Str = String.Empty;
        var IsOpen = m_CommonBusiness.GetFatoryAttributes(m_UserInfo.FactoryID, "检验合格限制");
        var StepDT = JsonConvert.DeserializeObject<DataTable>(context.Request["sdata"].ToString());
        var StrSql = @" SELECT  sc.INPUTNUM,N
                              FROM STEPCHECKPOINT SC
                             LEFT JOIN STEPINFO SO on so.WORKFLOWSTEPID = sc.WORKFLOWSTEPID and so.stepinfoid=sc.stepinfoid
                             left join STEPINFOBASE SOB ON SO.STEPINFOBASEID = SOB.STEPINFOBASEID
                             LEFT JOIN (SELECT COUNT(1) N,stepcheckpointid FROM stepcheckpointresult WHERE 1=1 AND containerid='{0}' 
                             GROUP BY stepcheckpointid) scr ON scr.stepcheckpointid=sc.stepcheckpointid
                             WHERE sc.INPUTNUM!=NVL(N,0)
                             AND SC.WORKFLOWSTEPID = '{1}'";
        foreach (DataRow dr in StepDT.Rows)
        {
            var selSQL = StrSql;
            if (!string.IsNullOrWhiteSpace(dr["stepinfoid"].ToString()))
            {
                selSQL += "AND so.stepinfoid='" + dr["stepinfoid"].ToString() + "'";
            }
            DataTable dt = DatabaseAccess.DBUtility.DatabaseHelper.Query_ReturnDatTable(string.Format(selSQL, dr["Containerid"].ToString(), dr["Workflowstepid"].ToString()));
            if (dt.Rows.Count > 0)
            {
                Count += 1;
                Str += dr["workflowstepName"];
                Str += string.IsNullOrWhiteSpace(dr["stepinfoName"].ToString()) ? "" : "--" + dr["stepinfoName"].ToString() + ",";
            }

            if (string.IsNullOrWhiteSpace(dr["Worker"].ToString()))
            {
                isNotwrok++;
            }
            else
            {
                if (string.IsNullOrWhiteSpace(dr["Checker"].ToString()))
                {
                    isNotcheck++;
                }
            }
        }
        if (Count > 0 && IsOpen.Equals("是"))
        {
            result.Message = "工序：" + Str.Substring(0, Str.LastIndexOf(",")) + " 存在未录入完的检测项";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (isNotwrok > 0)
        {
            result.Message = "存在没有报工信息的勾选记录";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (isNotcheck == 0)
        {
            result.Message = "请勾选存在报工没有检验的记录";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        var msg = string.Empty;
        result.Result = InsertContainercheckinfo(StepDT, para["workflowid"].ToString(), out msg);
        result.Message = result.Result ? "检验成功" : (string.IsNullOrWhiteSpace(msg) ? "检验失败" : msg);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private Boolean InsertContainercheckinfo(DataTable dt, string workflowid, out string msg)
    {
        var result = false;
        msg = string.Empty;
        foreach (DataRow dr in dt.Rows)
        {
            var chkDTO = new ContainerCheckInfoDTO();
            chkDTO.ContainerID = dr["ContainerId"].ToString();
            chkDTO.FactoryID = m_UserInfo.FactoryID;
            chkDTO.WorkflowstepID = dr["workflowstepid"].ToString();
            chkDTO.StepInfoID = string.IsNullOrWhiteSpace(dr["stepinfoId"].ToString()) ? string.Empty : dr["stepinfoId"].ToString();
            chkDTO.CheckerID = m_UserInfo.EmployeeID;
            chkDTO.CheckQty = Convert.ToInt32(dr["qty"].ToString());
            chkDTO.AcceptanceQty = Convert.ToInt32(dr["qty"].ToString());
            chkDTO.LossQty = 0;
            chkDTO.ReworkQty = 0;
            chkDTO.DefectQty = 0;
            chkDTO.ContainerCheckInfoID = System.Guid.NewGuid().ToString();
            chkDTO.CheckNote = string.Empty;
            chkDTO.CheckTypeNote = 2;
            chkDTO.FirstCheckBillNo = string.Empty;
            chkDTO.ContainerStepWorkReportID = dr["ContainerStepWorkReportID"].ToString();
            chkDTO.IsUse = 0;

            try
            {
                var para = new Dictionary<string, string>();
                para.Add("ContainerID", "'" + chkDTO.ContainerID + "'");
                para.Add("WorkflowstepID", "'" + chkDTO.WorkflowstepID + "'");
                para.Add("IsUse", chkDTO.IsUse.ToString());
                if (!string.IsNullOrWhiteSpace(chkDTO.StepInfoID.Trim()))
                {
                    para.Add("StepInfoID", "'" + chkDTO.StepInfoID.ToString() + "'");
                }
                DataTable dtChecker = m_CommonBusiness.GetTableInfoByField("containercheckinfo", para, null);
                if (dtChecker.Rows.Count > 0)
                {
                    msg = "工序" + dr["WorkFlowStepName"] + "已经有检验记录";
                    break;
                }
                result = m_CheckObj.AddZSContainerCheckInfo(chkDTO);
                if (!result) { msg = "检验异常"; break; }
                //施工单不判断完工序
                if (m_CheckObj.boolIsSGD(chkDTO.ContainerID))
                {
                    break;
                }
                //执行自动完工操作
                //在本工序或工步检验完成后判断本工序是否为完工工序，如为完工工序，且是最后一道工步或没有工步，更新EnginePartPlan表完工标志=1
                var paraa = new Dictionary<string, string>();
                paraa.Add("ContainerId", chkDTO.ContainerID);
                paraa.Add("StepId", chkDTO.WorkflowstepID);
                paraa.Add("StepInfoId", chkDTO.StepInfoID);
                paraa.Add("EmployeeID", m_UserInfo.EmployeeID);
                paraa.Add("FactoryCode", m_UserInfo.FactoryCode);
                if (m_PartPlanObj.boolCompleteStep(paraa))
                {
                    if (string.IsNullOrWhiteSpace(chkDTO.StepInfoID) || m_PartPlanObj.boolLastStepinfo(paraa))
                    {
                        if (!m_PartPlanObj.UpdateUseComplete(paraa))
                        {
                            msg = "完工标记更新异常";
                            result = false;
                            break;
                        }
                    }

                }
                else
                {
                    if (!m_PartPlanObj.boolCompleteStep(paraa))
                    {
                        int i_Stepinfo = m_DispatchObj.GetStepInfobyWorkflowId(workflowid).Rows.Count;
                        int i_CheckInfo = m_DispatchObj.GetCheckInfoDataByCid(paraa["ContainerId"]).Rows.Count;
                        //如果已经检验合格的记录=工序工步的记录,最后一道工序工步
                        if (i_Stepinfo == i_CheckInfo)
                        {
                            if (!m_PartPlanObj.UpdateUseComplete(para))
                            {
                                msg = "完工标记更新异常";
                                result = false;
                                break;
                            }
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                msg = "插入失败:" + ex.Message;
            }
        }

        return result;
    }

    private void InitUnqualified(HttpContext context)
    {
        var result = new uMESProcessResult();
        result.Result = true;
        //初始化缺陷原因-代码组
        DataTable dt = m_Common.GetLossReasonGroupData();
        dt.DefaultView.RowFilter = "lossreasongroupname like 'LY%'";
        dt = dt.DefaultView.ToTable();
        //责任单位
        DataTable UnitDT = m_Common.AddDutyUnit();
        result.DBTable = dt;
        result.ReturnData = UnitDT;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 缺陷原因-代码组ID--查询缺陷代码
    /// </summary>
    /// <param name="context"></param>
    private void GetLossReasonByGroupID(HttpContext context)
    {
        var result = new uMESProcessResult();
        result.Result = true;
        //初始化缺陷原因-代码组
        DataTable dt = m_Common.GetLossReasonByGroupID(context.Request["lossreasongroupid"].ToString());
        result.DBTable = dt;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 填入缺陷序号和短文本描述到文本框中
    /// </summary>
    /// <param name="context"></param>
    private void FillLossSequenceAndTxtData(HttpContext context)
    {
        var result = new uMESProcessResult();
        result.Result = true;
        DataTable dt = m_Common.GetLossSequenceAndDesc(context.Request["lossreasongroupid"].ToString(), context.Request["lossreasonid"].ToString());
        result.DBTable = dt;
        var para = new Dictionary<string, string>();
        if (dt.Rows.Count > 0)
        {
            para.Add("SEQUENCE", Convert.ToInt16(dt.Rows[0]["SEQUENCE"]).ToString("D4"));
            para.Add("DESCRIPTION", dt.Rows[0]["DESCRIPTION"].ToString());
        }
        result.ReturnData = para;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private void InsertUnqualifiedData(HttpContext context) 
    {
        var dpara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["ddata"].ToString());
        var upara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["udata"].ToString());
        var para=new Dictionary<string,string>();
        var result = new uMESProcessResult();
        para.Add("MaterialNoData", upara["MaterialNo"]);
        para.Add("ProductionOrderNumData", upara["mfgOrderName"]);
        para.Add("MesSpecData", upara["Spec"]);
        para.Add("MesSpecDescData", upara["SpecDesc"]);
        para.Add("ChildSpecData", "");
        para.Add("ChildSpecDescData", "");
        para.Add("StoveBatchNumData", upara["StoveBatchNum"]);
        para.Add("MachineBatchNumData", upara["BatchNum"]);
        para.Add("TypeData", upara["Type"]);
        para.Add("MachineTotalNumData", upara["TotalNum"]);
        para.Add("UnqualifiedNumData", upara["UnqualifiedNum"]);
        para.Add("VersionNoData", upara["VersionNo"]);
        para.Add("WorkCenterData", upara["WorkCenter"]);
        para.Add("MaterialBrandNumData", upara["MaterialBrandNum"]);
        para.Add("CodeCodeGroupsData", dpara["CodeCodeGroups"]);
        para.Add("DefectsTextData", dpara["Defects"]);
        para.Add("DefectsOrderNoData", dpara["DefectsOrderNo"]);
        para.Add("DefectsCodeGroupsData", dpara["DefectsCodeGroups"]);
        para.Add("DefectsCodeData", dpara["DefectsCode"]);
        para.Add("DefectsShortTxtData", dpara["DefectsShort"]);
        para.Add("DefectsLongTxtData", dpara["DefectsLong"]);
        para.Add("ApplicantId", m_UserInfo.EmployeeID);
        para.Add("UnqualifiedCategory", upara["UnqualifiedCategory"]);
        para.Add("TrialUnit", upara["TrialUnit"]);
        para.Add("PartCategory", upara["PartCategory"]);
        para.Add("DutyUnit", upara["DutyUnit"]);
        para.Add("EncodeCode", dpara["EncodeCode"]);
        para.Add("ContainerNonconformingInfoId", Guid.NewGuid().ToString());

        para.Add("ContainerID", dpara["ContainerID"]);
        para.Add("WorkflowStepID", dpara["WorkflowStepID"]);
        if (!string.IsNullOrWhiteSpace(dpara["StepInfoID"]))
        {
        para.Add("StepInfoID", dpara["StepInfoID"]);
        }
        result.Result = m_UnqualifiedData.InsertUnqualifiedData(para);
        result.Message = result.Result ? "提交不合格品信息成功" : "提交不合格品信息失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private void getScanContainerData(HttpContext context) 
    {
        var sql = @"SELECT ep.workflowid,
                       me.productfamilyname,
                       ep.machineno machine,
                       ep.mfgordername,
                       ep.containerno togetherflag,
                       ep.ContainerName,
                       ep.productname,
                       ep.productid,
                       ep.productdesc description,
                       ep.plannedstartdate plannedstartdate,
                       ep.plannedfinishdate plannedcompletiondate,
                       ep.concontainerid containerid,
                       ep.workflowstepname StepName,
                       ep.workflowname || ':' || wf.workflowrevision workflownamever,
                       ep.workflowdesc wfdesc,
                       p.MATERIALTRADEMARK,
                       p.PRODUCTREVISION PART_REVID 
                  FROM enginepartplan ep 
                  left join mfg_engine_data me on me.mfgorderid=ep.mfgorderid  
                  LEFT JOIN product p ON ep.productid = p.productid  
                  LEFT JOIN workflow wf ON wf.workflowid = ep.workflowid 
                  Inner JOIN (select distinct csd.containerid  from containerstepdispatch csd 
                                left join team t on t.teamid=csd.teamid 
                                left join containercheckinfo cch 
                                    on cch.containerid = csd.containerid  and csd.workflowstepid = cch.workflowstepid
                                    and nvl(csd.stepinfoid, '0') = nvl(cch.stepinfoid, '0') and cch.isuse = 0
                                where csd.Factoryid = '{0}'  and csd.isuse = 0 and instr(t.teamname,'故检'){1}0 {2} ) csd
                  on csd.containerid=ep.concontainerid         
                  WHERE ep.concontainerid>'0' AND ep.usecompleted = '0' ";
       
        var result = new uMESProcessResult();
        result.Result = true;
        var searchText = context.Request["searchText"].ToString();
        if (!string.IsNullOrWhiteSpace(searchText))
        {
            var sqlcm = string.Format(sql, m_UserInfo.FactoryID, "=", "and cch.CONTAINERCHECKINFOID is null and cch.checkerid is null");
            var selectSQL = sqlcm + "and ep.containerno like '%" + searchText + "%'";
            DataTable cdt = DatabaseHelper.Query_ReturnDatTable(selectSQL);
            var selectSQL2 = sqlcm + "and ep.mfgordername like '%" + searchText + "%'";
            DataTable mdt = DatabaseHelper.Query_ReturnDatTable(selectSQL2);
            cdt.Merge(mdt);
            result.DBTable = cdt; 
        }
        else {
            var sqlcm = string.Format(sql, m_UserInfo.FactoryID, "=", "and cch.CONTAINERCHECKINFOID is null and cch.checkerid is null");
            result.DBTable = DatabaseHelper.Query_ReturnDatTable(sqlcm);
        }
        if (!string.IsNullOrWhiteSpace(searchText))
        {
            var sqlcm = string.Format(sql, m_UserInfo.FactoryID, "=", "and cch.CONTAINERCHECKINFOID is not null and cch.checkerid is not null");
            var selectSQL = sqlcm + "and ep.containerno like '%" + searchText + "%'";
            DataTable cdt = DatabaseHelper.Query_ReturnDatTable(selectSQL);
            var selectSQL2 = sqlcm + "and ep.mfgordername like '%" + searchText + "%'";
            DataTable mdt = DatabaseHelper.Query_ReturnDatTable(selectSQL2);
            cdt.Merge(mdt);
            result.ReturnData = cdt;
        }
        else
        {
            var sqlcm = string.Format(sql, m_UserInfo.FactoryID, "=", "and cch.CONTAINERCHECKINFOID is not null and cch.checkerid is not null");
            result.ReturnData = DatabaseHelper.Query_ReturnDatTable(sqlcm);
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

}